package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.BuildArticleFreemakerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 刘旭
 * @Date 2022/9/1 12:15
 * @Description:
 */
public class BuildArticleFreemakerServiceImpl implements BuildArticleFreemakerService {
    @Autowired
    Configuration configuration;
    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    ApArticleMapper apArticleMapper;

    @SneakyThrows
    @Override
    public void buildArticleToMinio(ApArticle article, String content) {
        //校验参数
        if (StringUtils.isEmpty(content)) {
            throw new RuntimeException("内容为空");
        }
        //2.基于模板技术生成页面
        Map map = new HashMap();
        map.put("content", JSON.parseArray(content));
        Template template = configuration.getTemplate("article.ftl");
        StringWriter stringWriter = new StringWriter();
        template.process(map, stringWriter);

        //把页面存储到minio中
        ByteArrayInputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
        String staticUrl = fileStorageService.uploadHtmlFile(null, article.getId() + ".html", inputStream);
        //把上传到staticUrl存储到article表中
        article.setStaticUrl(staticUrl);
        apArticleMapper.updateById(article);

    }
}